<template>
	<view class="uni-container">
		<uni-forms ref="form" :value="formData" validateTrigger="bind">
			<uni-forms-item name="name" label=""><uni-easyinput placeholder="名称" v-model="formData.name" /></uni-forms-item>
			<uni-forms-item name="desc" label=""><uni-easyinput placeholder="描述" v-model="formData.desc" /></uni-forms-item>
			<uni-forms-item name="url" label=""><uni-easyinput placeholder="链接" v-model="formData.url" /></uni-forms-item>
			<uni-forms-item name="params" label=""><uni-easyinput placeholder="额外参数" v-model="formData.prams" /></uni-forms-item>
			<uni-forms-item name="img" label=""><uni-easyinput placeholder="图标" v-model="formData.img" /></uni-forms-item>
			<uni-forms-item name="status" label=""><uni-easyinput placeholder="状态：0 正常 1 禁用 2 审核中 3 审核拒绝" type="number" v-model="formData.status" /></uni-forms-item>
			<uni-forms-item name="sort" label=""><uni-easyinput placeholder="序号（越大越靠后）" type="number" v-model="formData.sort" /></uni-forms-item>
			<uni-forms-item name="type" label=""><uni-easyinput placeholder="类型: mp 小程序跳转 link 链接" v-model="formData.type" /></uni-forms-item>

			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;"><button class="uni-button" style="width: 100px;">返回</button></navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
import { validator } from '@/js_sdk/validator/lj-link.js';

const db = uniCloud.database();
const dbCmd = db.command;
const dbCollectionName = 'lj-link';

function getValidator(fields) {
	let reuslt = {};
	for (let key in validator) {
		if (fields.includes(key)) {
			reuslt[key] = validator[key];
		}
	}
	return reuslt;
}

export default {
	data() {
		return {
			formData: {
				name: '',
				desc: '',
				url: '',
				params: '',
				img: '',
				status: 0,
				sort: null,
				type: 'h5'
			},
			formOptions: {},
			rules: {
				...getValidator(['name', 'desc', 'url', 'params', 'img', 'status', 'sort', 'type'])
			}
		};
	},
	onReady() {
		this.$refs.form.setRules(this.rules);
	},
	methods: {
		/**
		 * 触发表单提交
		 */
		submit() {
			uni.showLoading({
				mask: true
			});
			this.$refs.form
				.submit()
				.then(res => {
					this.submitForm(res);
				})
				.catch(errors => {
					uni.hideLoading();
				});
		},

		submitForm(value) {
			// 使用 clientDB 提交数据
			db.collection(dbCollectionName)
				.add(value)
				.then(res => {
					uni.showToast({
						title: '新增成功'
					});
					this.getOpenerEventChannel().emit('refreshData');
					setTimeout(() => uni.navigateBack(), 500);
				})
				.catch(err => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					});
				})
				.finally(() => {
					uni.hideLoading();
				});
		}
	}
};
</script>
